package com.msy.mai.framework.security.core.handler;

import cn.hutool.core.util.ReUtil;
import com.msy.mai.common.core.constants.BeanConst;
import com.msy.mai.common.core.utils.SpringUtils;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 获取所有Url配置
 *
 * @author Lion Li
 */
@Data
public class AllUrlHandler implements InitializingBean {

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");

    private List<String> urls = new ArrayList<>();

    @Override
    public void afterPropertiesSet() {
        Set<String> set = new HashSet<>();
        RequestMappingHandlerMapping mapping = SpringUtils.getBean(BeanConst.REQUEST_MAPPING_HANDLER_MAPPING, RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        for (RequestMappingInfo info : map.keySet()) {
            // 兼容低版本spring 使用 PatternsRequestCondition 而不是 PathPatternsRequestCondition
            PatternsRequestCondition patternsCondition = info.getPatternsCondition();
            Set<String> patterns = patternsCondition.getPatterns();
            for (String pattern : patterns) {
                // 获取注解上边的 path 替代 path variable 为 *
                set.add(ReUtil.replaceAll(pattern, PATTERN, "*"));
            }
        }
        urls.addAll(set);
    }

}
